<?php

/*
    String class

        Author:     Alfredo Mungo
        License:    LGPL
        Copyright:  2012

*/

/*
    String class
    
    Constructors:
        String(str)
        String(array, glue_delimiter)
    
    Static Methods:
        N/A
    
    Methods:
        length()
        value()
        append(str)
        toUpper()
        toLower()
        toProper()
        getChar(i)
        setChar(i, c)
        find(str, offset)
        replace(pattern, replacement, count)
        explode(delim, limit)
        trim(chars)
*/
class String {

    private $str;

    function __construct($str, $delim = null) {
    
        if($delim == null) {
            if(is_string($str))
                $this->str = $str;
            else
                throw new Exception('Not a string');
        } else {
            if(is_array($arr))
                $this->str = implode($delim, $arr);
            else
                throw new Exception('Not an array');
        }
    }
    
    public function length() { return strlen($this->str); }
    public function value() { return $this->str; }
    
    public function append($str) { $this->str .= $str; }
    
    public function toUpper() { return strtoupper($this->str); }
    public function toLower() { return strtolower($this->str); }
    public function toProper() { return ucfirst(strtolower($this->str)); }
    
    public function getChar($i) { return ($i < strlen($this->str) && $i >= 0)? $this->str[$i]: null; }
    public function setChar($i, $c) { if($i < strlen($this->str) && $i >= 0) $this->str[$i] = $c; }
    
    /*
        Find $str in the string, starting from character $offset.
        
        Return:
            (bool) false: not found
            (int) 0..n: position of the first char of $str in the string
    */
    public function find($str, $offset = 0) { return strpos($this->str, $str, $offset); }
    
    // Return a copy of the string with $count $pattern substrings replaced with $replacement
    public function replace($pattern, $replacement, $count = null) { $this->str = str_replace($pattern, $replacement, $this->str, $count); }
    
    public function explode($delim, $limit = null) { return $limit == null? explode($delim, $this->str): explode($delim, $this->str, $limit); }
    
    public function trim($clist = null) { $this->str = $clist == null? trim($this->str): trim($this->str, $clist); }
}

?>